<!--登录弹窗组件-->
<template>
  <el-dialog
    class="user-login-dialog"
    v-model="dialogVisible"
    :align-center="true"
    :width="420"
    :append-to-body="true"
    :show-close="false"
    draggable
  >
    <div class="login-count">
      <!-- 登录弹窗 -->
      <div class="wrapper-count flex" :class="pcConfig.wxScanSwitch === 2 ? 'w-908px' : 'w-540px'">
        <span class="closeBtn iconfont icon-danchuangguanbi" @click="closeLogin"></span>
        <div v-if="pcConfig.wxScanSwitch === 2" class="wrapper w-454px">
          <div class="font18 mb-40px">手机扫码登录</div>
          <div>打开<span class="font-color">微信</span>点击右上角扫一扫</div>
          <div class="w-210px h-210px b-rd-8px borderSol-eee flex-center mQ">
            <el-image
              :src="`https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${pcConfig.ticket}`"
              class="w-192px h-192px"
              @click="handleQrCodeClick"
            ></el-image>
          </div>
        </div>
        <div class="wrapper w-540px">
          <div
            class="form-container"
            :class="{ 'register-mode': current === 3 }"
            style="border-left: 1px solid #eeeeee;"
          >
            <div class="title" :style="{ paddingBottom: '20px' }">
              <!-- <span class="item_title" @click="current = 1" :class="current === 1 ? 'font18' : ''">登录/注册</span> -->
              <span class="item_title" @click="current = 2" :class="current === 2 ? 'font18' : ''">密码登录</span>
              <span class="item_title register-title" @click="current = 3" :class="current === 3 ? 'font18' : ''"
                >立即注册</span
              >
            </div>
            <!--            <div class="iconfont icon-erweima" @click="current = 3"></div>-->
            <!--手机号-->

            <!--验证码-->
            <!-- <div
              v-show="current === 1 || current === 4 || current === 5"
              class="item phone verificat acea-row row-between-wrapper"
            >
              <div class="acea-row row-middle"></div>
                <div class="number mr-14px"><span class="iconfont icon-yanzhengma"></span></div>
                <input
                  type="text"
                  autocomplete="new-password"
                  placeholder="请输入验证码"
                  v-model="formData.captcha"
                  class="text-14px text-#333"
                />
              </div>
              <button
                class="code font-color cursors"
                :disabled="disabled"
                :class="disabled === true ? 'on' : ''"
                @click="handleSendcode"
              >
                {{ text }}
              </button>
            </div> -->

            <!--密码登录-->
            <div v-show="current === 2">
              <LoginForm ref="loginFormRef" v-model:formData="formData" @validate="onLoginValidate" />
            </div>

            <!--注册表单-->
            <div v-show="current === 3">
              <RegisterForm
                ref="registerFormRef"
                v-model:registerData="registerData"
                @selectUserType="selectUserType"
                @validate="onRegisterValidate"
              />
            </div>
            <!--底部按钮-->
            <div class="checkbox-wrapper item_protocol acea-row row-middle">
              <label class="well-check" style="line-height: 2;">
                <input type="checkbox" name="" value="" :checked="isAgreement" @click="isAgreement = !isAgreement" />
                <i class="iconfont mr-7px icon" style="top: 11px;"></i>
                <span>我已阅读并同意</span>
              </label>
              <nuxt-link
                :to="{ path: `/users/agreement_rules`, query: { type: 'userinfo', name: '用户协议' } }"
                target="_blank"
                class="show_protocol"
                >《用户协议》
              </nuxt-link>
              与
              <nuxt-link
                :to="{ path: `/users/agreement_rules`, query: { type: 'userprivacyinfo', name: '隐私协议' } }"
                target="_blank"
                class="show_protocol"
                >《隐私协议》
              </nuxt-link>
            </div>
            <!-- <div v-if="current !== 3" class="signIn bg-color" @click="handleLogin">登录</div> -->
            <div v-if="current !== 3" class="signIn bg-color" @click="getloginPassword">登录</div>
            <div v-else class="signIn bg-color" @click="handleRegisterSubmit">立即注册</div>
            <div v-if="pcConfig.wxScanSwitch === 1" @click="wechatLoginPC" class="flex-center mt-18px cursor-pointer">
              <img src="@/assets/images/wechat.png" class="w-22px h-22px" />
              <div class="ml-8px">微信登录</div>
            </div>
          </div>
        </div>
        <!--        <div class="wxLogin wrapper" v-if="current === 3">-->
        <!--          <div class="inner">扫码登录</div>-->
        <!--          <div class="iconfont icon-zhanghaodenglu1" @click="current = 1"></div>-->
        <!--          <div class="wxCode">-->
        <!--            <span class="iconfont icon-erweimabianjiao"></span>-->
        <!--            <span class="iconfont icon-erweimabianjiao"></span>-->
        <!--            <span class="iconfont icon-erweimabianjiao"></span>-->
        <!--            <span class="iconfont icon-erweimabianjiao"></span>-->
        <!--            <img v-if="qrCode" :src="qrCode" />-->
        <!--          </div>-->
        <!--          <div class="tip">请使用微信扫一扫登录</div>-->
        <!--        </div>-->
      </div>
    </div>
    <ClientOnly>
      <VerifitionVerify ref="verifyRef" :phone="formData.phone" @success="handlerOnVerSuccess"></VerifitionVerify>
    </ClientOnly>
  </el-dialog>
</template>
<script setup lang="ts">
import { PhoneReg } from '~/utils/validate'
import { Debounce } from '~/utils/util'
import {
  loginMobile,
  loginPassword,
  registerVerify,
  userPhoneCodeApi,
  pcConfigApi,
  pcWechatAgreeInfoApi,
  userRegisterApi,
  sendRegisterCodeApi,
} from '~/server/userApi'
import feedback from '~/utils/feedback'
import useOrder from '~/composables/useOrder'
import { ref, reactive, onUnmounted, onMounted, shallowRef, defineAsyncComponent } from 'vue'
import { ItemObject } from '~/types/global'
import { useAppStore } from '~/stores/app'
import { useUserStore } from '~/stores/user'
import { usePolling } from '~/composables/usePolling'
import { useSmsCode } from '~/composables/verifyCode'
import { linkNavigateTo } from '~/utils/util'
const LoginForm = defineAsyncComponent(() => import('./LoginForm.vue'))
const RegisterForm = defineAsyncComponent(() => import('./RegisterForm.vue'))

// 子组件引用
const loginFormRef = ref()
const registerFormRef = ref()

const appStore = useAppStore()
const userStore = useUserStore()

//pc登录配置
const pcConfig = reactive({
  openAppid: '',
  ticket: '',
  wxScanSwitch: 0,
})
const getPcConfig = async () => {
  const data = await pcConfigApi()
  Object.assign(pcConfig, data)
  // 获取pc扫码登录配置
  await emit('getwxScanSwitch', pcConfig.wxScanSwitch)
  if (pcConfig.wxScanSwitch === 2) {
    getWechatAgreeInfo() // Initial check
    startPolling(getWechatAgreeInfo, 3000) // Start polling every 3 seconds
  }
}

// // 轮询相关状态
const pollingTimer = ref<number | null>(null)
const pollingCount = ref(0)
const isPolling = ref(false)

//PC商城微信公众号用户同意登录信息
const { startPolling, stopPolling } = usePolling()
const getWechatAgreeInfo = async () => {
  try {
    const data = await pcWechatAgreeInfoApi(pcConfig.ticket)
    console.log('data?.wechatPublicUserAgreeStatus', data?.wechatPublicUserAgreeStatus)
    if (data?.wechatPublicUserAgreeStatus) {
      feedback.loading('加载中..')
      // Handle successful agreement
      await wechatLoginSuccess(data)
      pcConfig.ticket = ''
      DialogClose() // Close the dialog after successful login
      stopPolling()
    }
  } catch (error) {
    stopPolling()
  }
}

// 网站登录微信
const hosts = ref(location.origin + location.pathname)
const route = useRoute()

const wechatLoginPC = async () => {
  console.log(route, 'route')
  if (!isAgreement.value) return feedback.msgWarning('请勾选协议')
  appStore.getWechatRoutePath(route.fullPath)
  //const encodedQuery = encodeURIComponent(location.origin+route.path);
  const encodedQuery = encodeURIComponent(location.origin + '/authorizedLogin')
  console.log(location.origin + route.path, 'encodedQueryencodedQuery')
  window.location.href = `https://open.weixin.qq.com/connect/qrconnect?appid=${pcConfig.openAppid}&redirect_uri=${encodedQuery}&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirec`
}

const emit = defineEmits(['onLoginSucceeded', 'openBindPhone', 'getwxScanSwitch'])
// 微信扫码登录成功
const wechatLoginSuccess = async (data: any) => {
  //未注册的时候调起绑定手机号去绑定手机号
  if (data.type === 'register') {
    await emit('openBindPhone', data)
  }
  if (data.type === 'login') {
    await loginSuccess(data)
  }
  feedback.closeLoading()
}
//
// 打开登录弹窗
const { bool: dialogVisible, DialogOpen, DialogClose } = useDialog()
const open = () => {
  formData.phone = ''
  formData.captcha = ''
  getPcConfig()
  DialogOpen()
  console.log('pcConfig.wxScanSwitchpcConfig.wxScanSwitch', pcConfig.wxScanSwitch)
}
defineExpose({ open })
//
//关闭登录弹窗
const closeLogin = () => {
  DialogClose()
  stopPolling()
  stopCountdown()
}
//
// Stop polling when component is unmounted
onUnmounted(() => {
  stopPolling()
})

//是否勾选协议
const isAgreement = ref(false)

// 登录提交数据
const formData = reactive({
  captcha: '',
  phone: '',
  spreadPid: 0,
  password: '',
})

// 注册提交数据
const registerData = reactive({
  username: '',
  password: '',
  email: '',
  phone: '',
  confirmPassword: '',
  captcha: '000000', // 写死验证码为000000
  userType: '供应商',
  isAgreement: false,
})

//扫码登录二维码
const qrCode = ref('')

//验证码
const { disabled, text, handleCodeSend, stopCountdown } = useSmsCode()
const isSendCode = ref(false)

// 手机号码验证
const inputPhone = (e: any) => {
  isSendCode.value = PhoneReg.test(e)
}

// 获取验证码
const verifyRef = shallowRef()
const handleSendcode = () => {
  if (!formData.phone) return feedback.msgWarning('请填写手机号')
  if (!isAgreement.value) return feedback.msgWarning('请勾选协议')
  verifyRef.value.show()
}

// 发送成功后的回调
const handlerOnVerSuccess = async (e: any) => {
  await registerVerify({ phone: formData.phone })
  feedback.msgSuccess('发送成功')
  handleCodeSend()
}

// 选择用户类型
const selectUserType = (type: string) => {
  registerData.userType = type
}

// 登录表单校验回调
const onLoginValidate = (isValid: boolean) => {
  console.log('登录表单校验结果:', isValid)
}

// 注册表单校验回调
const onRegisterValidate = (isValid: boolean) => {
  console.log('注册表单校验结果:', isValid)
}

// 发送注册验证码
const handleSendRegisterCode = async () => {
  if (!registerData.phone) {
    feedback.msgError('请填写手机号')
    return
  }
  if (!PhoneReg.test(registerData.phone)) {
    feedback.msgError('请输入正确的手机号码')
    return
  }

  try {
    await registerVerify({ phone: registerData.phone })
    feedback.msgSuccess('验证码发送成功')
    handleCodeSend()
  } catch (error) {
    feedback.msgError('验证码发送失败: ' + (error?.message || '未知错误'))
  }
}

// 注册提交
const handleRegisterSubmit = async () => {
  // 检查协议是否勾选
  if (!isAgreement.value) return feedback.msgError('请勾选协议')

  // 使用子组件校验
  if (!registerFormRef.value) return

  try {
    const isValid = await registerFormRef.value.validate()
    if (!isValid) return

    feedback.loading('正在注册...')

    // 第1步：先调用发送注册验证码接口，验证手机号是否可用
    await sendRegisterCodeApi(registerData.phone)

    // 第2步：调用注册API，使用写死的验证码000000
    await userRegisterApi({
      username: registerData.username,
      password: registerData.password,
      phone: registerData.phone,
      email: registerData.email,
      userType: registerData.userType,
      captcha: registerData.captcha, // 这里使用写死的000000
    })
    feedback.msgSuccess('注册成功')
    feedback.closeLoading() // 关闭loading效果
    current.value = 2 // 返回登录
    formData.phone = registerData.phone
    formData.password = registerData.password // 同时赋值密码

    // 重置registerData，保留captcha、userType、isAgreement三个字段
    Object.assign(registerData, {
      username: '',
      password: '',
      email: '',
      phone: '',
      confirmPassword: '',
      captcha: '000000', // 写死验证码为000000
      userType: '',
      isAgreement: false,
    })

    // closeLogin() // 关闭弹框
  } catch (error) {
    feedback.closeLoading() // 关闭loading效果
    feedback.msgError('注册失败: ' + (error?.message || '未知错误'))
  }
}
// 二维码点击处理
const handleQrCodeClick = () => {
  console.log('二维码被点击')
}

const agreementConfirm = async () => {
  if (isAgreement.value) {
    return
  }
  await feedback.confirm('确认已阅读并同意《服务协议》和《隐私政策》')
  isAgreement.value = true
}

// 登录按钮提交
//显示标识 1快速登录 2密码登录
const current = ref<number>(2)
const { onGetCartCount } = useOrder()
const handleLogin = Debounce(async () => {
  if (!formData.phone) return feedback.msgError('请填写手机号码')
  if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(formData.phone)) return feedback.msgError('请输入正确的手机号码')
  if (!isAgreement.value) return feedback.msgError('请勾选用户隐私协议')
  //快速登录
  if (current.value === 2) {
    await getLoginMobile()
  } else {
    //账号密码登录
    if (!formData.password) return feedback.msgError('请填写密码')
    await getloginPassword()
  }
  await closeLogin()
  await onGetCartCount()
}, 500)

//密码登录
const getloginPassword = async () => {
  if (!isAgreement.value) return feedback.msgError('请勾选协议')

  // 使用子组件校验
  if (!loginFormRef.value) return

  try {
    const isValid = await loginFormRef.value.validate()
    if (!isValid) return

    // 显示loading效果
    feedback.loading('正在登录...')

    const params = {
      phone: formData.phone,
      password: formData.password,
      spreadPid: formData.spreadPid,
    }
    const data = await loginPassword(params)
    await loginSuccess(data)

    // 登录成功后关闭loading和弹框
    feedback.closeLoading()
    feedback.msgSuccess('登录成功')
    closeLogin()
  } catch (error) {
    // 登录失败时关闭loading并显示错误信息
    feedback.closeLoading()
    feedback.msgError('登录失败: ' + (error?.message || '未知错误'))
  }
}

//快速/验证码登录
const getLoginMobile = async () => {
  const params = {
    phone: formData.phone,
    captcha: formData.captcha,
    spreadPid: formData.spreadPid,
  }
  const data = await loginMobile(params)
  await loginSuccess(data)
}
//登录成功之后
const loginSuccess = async (data: ItemObject) => {
  userStore.login(data.token)
  userStore.setUserInfo(data)
  text.value = '获取验证码'
  stopCountdown()
  await appStore.getGlobalConfig()
  await emit('onLoginSucceeded', data) //登录成功后操作
}
</script>
<style scoped lang="scss">
@import '@/assets/scss/checkbox.scss';
@import '@/assets/scss/login.scss';
input::-webkit-input-placeholder {
  /* 修改placeholder颜色  */
  color: #cccccc;
}
.mQ {
  margin: 34px auto;
}
.aa {
  width: 430px;
}
/* 表单容器动态背景 */
.form-container {
  min-height: 400px;
  background: #fff;
  transition: all 0.3s ease;
  position: relative;
  padding: 20px;
  border-radius: 8px;

  &.register-mode {
    min-height: 600px;
    background: #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

/* 立即注册标题样式 */
.register-title {
  color: #1890ff !important;
}

/* 注册表单样式 */
.form-subtitle {
  font-size: 16px;
  color: #333;
  text-align: center;
  margin-bottom: 20px;
  font-weight: 500;
}

.user-type-section {
  margin: 20px 0;

  .user-type-title {
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
  }

  .user-type-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;

    .user-type-item {
      padding: 12px;
      border: 1px solid #ddd;
      border-radius: 4px;
      text-align: center;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.3s;

      &:hover {
        border-color: #ff4444;
      }

      &.selected {
        border-color: #ff4444;
        background-color: #ffe6e6;
        color: #ff4444;
      }
    }
  }
}
</style>
